﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;
using WebCommit.Common.Helpers;

namespace WebCommit.Common.Factories
{
	public class SvcFactory
	{
		private static Hashtable hashTable = null;
		static SvcFactory()
		{
			if (hashTable == null)
			{
				hashTable = new Hashtable();
				string fileName = Utility.GetCurrentAppPath() + "\\Config\\SvcConfig\\SvcFactory.cfg.xml";
				XmlDocument doc = new XmlDocument();
				doc.Load(fileName);
				foreach (XmlNode node in doc.SelectNodes("SvcConfig/Svc"))
				{
					string nameStr = node.Attributes["name"].Value;
					string infaceStr = node.Attributes["interface"].Value;
					string intancStr = node.Attributes["instance"].Value;
					Type inface = Type.GetType(infaceStr);
					object obj = Activator.CreateInstance(Type.GetType(intancStr));
					dynamic svc = new { Name = nameStr, Interface = inface, Instance = obj };
					hashTable.Add(inface, svc);
				}
			}
		}

		public static T GetInstance<T>()
		{
			Type t = typeof(T);
			if (!hashTable.ContainsKey(t))
				return default(T);

			dynamic obj = hashTable[t];

			return (T)obj.Instance;
		}
	}
}
